package org.example.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.example.aop.Annno;
import org.example.config.R;
import org.example.domain.Menu;
import org.example.domain.User;
import org.example.service.MenuService;
import org.example.service.RoleService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
    public static final String salt="abc";

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("getCode")
    public void getCode(String uuid, HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());

        redisTemplate.opsForValue().set(uuid,captcha.getCode(),5, TimeUnit.MINUTES);
    }

    @Annno(value = "登录")
    @RequestMapping("login")
    public R login(@RequestBody User user){
        String code = redisTemplate.opsForValue().get(user.getUuid()).toString();
        if (!user.getCode().equals(code)){
            return R.failed("验证码错误");
        }

        System.out.println("username================"+user.getUsername());
        User dbUser=userService.getUser(user.getUsername());
        if (dbUser==null){
            return R.failed("账户不存在");
        }

        String pwd = DigestUtil.md5Hex(user.getPassword() + salt);

        if (!dbUser.getPassword().equals(pwd)){
            return R.failed("密码错误");
        }

        String token = JWT.create()
                .setPayload("uid", dbUser.getId())
                .setSigner(JWTSignerUtil.none())
                .sign();

        HashMap map = new HashMap();
        map.put("uid", dbUser.getId());
        map.put("username", dbUser.getUsername());
        map.put("email", dbUser.getEmail());
        map.put("tel", dbUser.getTel());
        map.put("token", token);

        return R.successed(map);
    }

    @Autowired
    MenuService menuService;

    @Autowired
    RoleService roleService;

    @RequestMapping("getTree")
    public R getTree(@RequestParam("id") Integer id){

        Integer auth=roleService.getAuthById(id);

        List<Menu> list=null;

        if (auth!=2){
            list=menuService.getListByid(id);
        }else {
            list=menuService.getList();
        }



        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();

//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<Menu, String>build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getParentId()+"");
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("path", treeNode.getPath());
                    tree.putExtra("component", treeNode.getComponent());
                });
        return R.successed(treeNodes);
    }

    @RequestMapping("getUserName")
    public List<User> getUserName(){
        List<User> list=userService.getUserName();
        return list;
    }


}
